<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.3.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&display=swap&subset=latin,latin-ext">
<link rel="stylesheet" href="/blog/lib/font-awesome/css/font-awesome.min.css">


<script id="hexo-configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    hostname: new URL('https://guodh.gitee.io/blog').hostname,
    root: '/blog/',
    scheme: 'Pisces',
    version: '7.7.1',
    exturl: false,
    sidebar: {"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},
    copycode: {"enable":true,"show_result":true,"style":null},
    back2top: {"enable":true,"sidebar":false,"scrollpercent":false},
    bookmark: {"enable":false,"color":"#222","save":"auto"},
    fancybox: false,
    mediumzoom: false,
    lazyload: false,
    pangu: false,
    comments: {"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},
    algolia: {
      appID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    },
    localsearch: {"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},
    path: 'search.xml',
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}
  };
</script>

  <meta name="description" content="分布式事务应该是大家耳熟能详的东西了吧。作为一个当今时代”微服务蓬勃发展”背景下的程序员，如果出去面试被问到分布式事务还不能哔哔几句的话，估计是要凉凉的节奏。对于分布式事务，大家比较了解的2PC，3PC，以及最终一致性，当然也包括Saga的补偿模式。关于Sage大家可以看   https:&#x2F;&#x2F;servicecomb.incubator.apache.org&#x2F;cn&#x2F;docs&#x2F;distributed-">
<meta property="og:type" content="article">
<meta property="og:title" content="分布式事务">
<meta property="og:url" content="https://guodh.gitee.io/blog/2018/10/20/2018/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/index.html">
<meta property="og:site_name" content="蛋蛋的小屋">
<meta property="og:description" content="分布式事务应该是大家耳熟能详的东西了吧。作为一个当今时代”微服务蓬勃发展”背景下的程序员，如果出去面试被问到分布式事务还不能哔哔几句的话，估计是要凉凉的节奏。对于分布式事务，大家比较了解的2PC，3PC，以及最终一致性，当然也包括Saga的补偿模式。关于Sage大家可以看   https:&#x2F;&#x2F;servicecomb.incubator.apache.org&#x2F;cn&#x2F;docs&#x2F;distributed-">
<meta property="og:locale">
<meta property="og:image" content="https://servicecomb.incubator.apache.org/assets/images/saga/Saga.007.jpeg">
<meta property="og:image" content="https://olwr1lamu.qnssl.com/Connection.png">
<meta property="article:published_time" content="2018-10-20T01:25:56.000Z">
<meta property="article:modified_time" content="2018-10-28T12:59:18.000Z">
<meta property="article:author" content="RunningEgg">
<meta property="article:tag" content="技术">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://servicecomb.incubator.apache.org/assets/images/saga/Saga.007.jpeg">

<link rel="canonical" href="https://guodh.gitee.io/blog/2018/10/20/2018/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome: false,
    isPost: true
  };
</script>

  <title>分布式事务 | 蛋蛋的小屋</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-meta">

    <div>
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">蛋蛋的小屋</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
        <p class="site-subtitle">来了就看看吧，没有刀剑只有故事</p>
  </div>

  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-fw fa-home"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-fw fa-user"></i>About</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>Archives</a>

  </li>
        <li class="menu-item menu-item-book">

    <a href="/blog/book/" rel="section"><i class="fa fa-fw fa-archive"></i>book</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="https://guodh.gitee.io/blog/2018/10/20/2018/%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.gif">
      <meta itemprop="name" content="RunningEgg">
      <meta itemprop="description" content="写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="蛋蛋的小屋">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          分布式事务
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2018-10-20 09:25:56" itemprop="dateCreated datePublished" datetime="2018-10-20T09:25:56+08:00">2018-10-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2018-10-28 20:59:18" itemprop="dateModified" datetime="2018-10-28T20:59:18+08:00">2018-10-28</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>分布式事务应该是大家耳熟能详的东西了吧。作为一个当今时代”微服务蓬勃发展”背景下的程序员，如果出去面试被问到分布式事务还不能哔哔几句的话，估计是要凉凉的节奏。对于分布式事务，大家比较了解的2PC，3PC，以及最终一致性，当然也包括Saga的补偿模式。关于Sage大家可以看 </p>
<blockquote>
<p><a href="https://servicecomb.incubator.apache.org/cn/docs/distributed-transactions-saga-implementation/">https://servicecomb.incubator.apache.org/cn/docs/distributed-transactions-saga-implementation/</a> </p>
</blockquote>
<p>由Servicecomb提供的实现，毕竟是Apache项目稳定性有保证。</p>
<p>当把我们的目光放回来，虽说我们都知道分布式事务有这几种模式，但是只见过猪肉没见过猪跑呀。还好随着国内开源环境的逐渐变好，有很多厉害的人为我们实现了这些规范。让我们这些萌新，即使不要去到大厂一样也能看到猪跑。那么文本的目的就是查看源码，看看他们到底是如何“实现”分布式事务的。注意是实现，我们不关注细节，但是要明确他们是如何将我们需周知的概念转化为可实现的代码。</p>
<a id="more"></a>

<table>
<thead>
<tr>
<th align="left">介绍</th>
<th align="left">地址</th>
</tr>
</thead>
<tbody><tr>
<td align="left">2PC</td>
<td align="left"><a href="https://github.com/codingapi/tx-lcn">https://github.com/codingapi/tx-lcn</a></td>
</tr>
<tr>
<td align="left">通过消息确保调用持续下去</td>
<td align="left"><a href="https://github.com/yu199195/myth">https://github.com/yu199195/myth</a></td>
</tr>
<tr>
<td align="left">TCC</td>
<td align="left"><a href="https://github.com/yu199195/hmily">https://github.com/yu199195/hmily</a></td>
</tr>
</tbody></table>
<h2 id="XA规范"><a href="#XA规范" class="headerlink" title="XA规范"></a>XA规范</h2><p>XA就是X/Open DTP定义的交易中间件与数据库之间的接口规范（即接口函数），交易中间件用它来通知数据库事务的开始、结束以及提交、回滚等。XA接口函数由数据库厂商提供。众多的数据库都提供了这类实现，包括MySQL，PostgreSql等。</p>
<blockquote>
<p>一直以来，MySQL数据库是支持分布式事务的，但是只能说是有限的支持，具体表现在：<br>已经prepare的事务，在客户端退出或者服务宕机的时候，2PC的事务会被回滚在服务器故障重启提交后，相应的Binlog被丢失。知道Mysql5.7版本才被修复。</p>
</blockquote>
<h2 id="JTA"><a href="#JTA" class="headerlink" title="JTA"></a>JTA</h2><p>既然数据库是支持分布式事务的，那么对于Java来说一定有使用的姿势。那就是JTA，Java Transcation API ，J2EE提供的规范。首先，需要添加必要的依赖。</p>
<figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 还是08年的包，看来是真的没人用 --&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;javax.transaction&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;jta&lt;/artifactId&gt;</span><br><span class="line">    &lt;version&gt;1.1&lt;/version&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<p>然后使用起来就比较简单了，如下就是使用的API：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">userTransaction.begin();</span><br><span class="line">userTransaction.commit();</span><br><span class="line">userTransaction.rollback();</span><br></pre></td></tr></table></figure>
<h2 id="关于XA以及JTA的总结"><a href="#关于XA以及JTA的总结" class="headerlink" title="关于XA以及JTA的总结"></a>关于XA以及JTA的总结</h2><p>我们可以看到对于XA和JTA更多的是需要数据库层面的支持，JTA只是暴露了一个接口供使用者去触发数据库的XA事务。尴尬的是呢，如今都是使用Mysql。对于Mysql，大部分人包括我的认知都是只是一个存储的数据库，很多东西都需要软件层面去处理。因为Mysql真的很脆弱。PS：为啥PostgreSql用的人少，我还是挺疑惑的，最近有空就研究研究两者的不同。</p>
<p>那么接下来就让我们看看如何从软件层面，来实现分布式事务。</p>
<h2 id="基于2PC的分布式事务"><a href="#基于2PC的分布式事务" class="headerlink" title="基于2PC的分布式事务"></a>基于2PC的分布式事务</h2><img src="https://servicecomb.incubator.apache.org/assets/images/saga/Saga.007.jpeg" width="80%" height="80%" alt="2PC"/>

<p>如图所示，2PC最重要的是实现了一个事务管理的角色，所有参与事务的服务都需要与它交流。</p>
<h3 id="不同容器之间如何控制事务的回滚"><a href="#不同容器之间如何控制事务的回滚" class="headerlink" title="不同容器之间如何控制事务的回滚"></a>不同容器之间如何控制事务的回滚</h3><ol>
<li><p>重写了 DataSource </p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Around(&quot;execution(* javax.sql.DataSource.getConnection(..))&quot;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> Connection <span class="title">around</span><span class="params">(ProceedingJoinPoint point)</span><span class="keyword">throws</span> Throwable</span>&#123;</span><br><span class="line">    Connection connection = lcnConnection.getConnection(point);</span><br><span class="line">    <span class="keyword">return</span> connection;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<img src="https://olwr1lamu.qnssl.com/Connection.png" width="80%" height="80%" alt="Connection结构"/>
</li>
<li><p>通过代理模式，保证了提交事务的时候还是调用到同一台服务器上，给dubbo的负载均衡包裹了一层</p>
</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> invokers 可供选择的服务器</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> Invoker  由dubbo本身提供的负载均衡策略所选择出来的服务</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &lt;T&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@throws</span> RpcException</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">Invoker&lt;T&gt; <span class="title">proxy</span><span class="params">(List&lt;Invoker&lt;T&gt;&gt; invokers, Invoker&lt;T&gt; invoker)</span> <span class="keyword">throws</span> RpcException </span>&#123;</span><br><span class="line">		TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();</span><br><span class="line">        <span class="keyword">if</span>(txTransactionLocal==<span class="keyword">null</span>)&#123;</span><br><span class="line">            <span class="keyword">return</span> invoker;</span><br><span class="line">        &#125;</span><br><span class="line">        TxTransactionLocal txTransactionLocal = TxTransactionLocal.current();</span><br><span class="line">        String groupId = txTransactionLocal.getGroupId();</span><br><span class="line">        String uniqueKey = invoker.getUrl().getServiceInterface();</span><br><span class="line">        String key = MD5Util.md5((groupId + <span class="string">&quot;_&quot;</span> + uniqueKey).getBytes());</span><br><span class="line">        <span class="comment">//请求tm获取模块信息</span></span><br><span class="line">        Invoker old = getInvoker(txTransactionLocal, invokers, key);</span><br><span class="line">        putInvoker(key, txTransactionLocal, invoker);</span><br><span class="line">        <span class="keyword">return</span> invoker;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li><p>通过注解使用切面，在上下文中来传递事务信息<br>从InheritableThreadLocal拿出ThreadLocal里的</p>
</li>
<li><p>通过Netty独立构建一个RPC框架，来持久化保存调用的信息<br>这个很关键，分布式事务是针对各种异常情况所处理的框架，包括服务器宕机等各种极端情况，数据的持久化就显得尤其重要。</p>
</li>
</ol>
<h2 id="基于消息的分布式事务"><a href="#基于消息的分布式事务" class="headerlink" title="基于消息的分布式事务"></a>基于消息的分布式事务</h2><p>基于消息的分布式事务并没有提供回滚，而是通过Rocketmq来重新。当调用链路中某台服务器由于宕机而导致事务终端，框架通过多次发送MQ来恢复当时的状态。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">begin</span><span class="params">(<span class="keyword">final</span> ProceedingJoinPoint point)</span> </span>&#123;</span><br><span class="line">    MythTransaction mythTransaction = buildMythTransaction(point, MythRoleEnum.START.getCode(), MythStatusEnum.BEGIN.getCode(), <span class="string">&quot;&quot;</span>);</span><br><span class="line">    <span class="comment">//发布事务保存事件，异步保存</span></span><br><span class="line">    publishEvent.publishEvent(mythTransaction, EventTypeEnum.SAVE.getCode());</span><br><span class="line">    <span class="comment">//当前事务保存到ThreadLocal</span></span><br><span class="line">    CURRENT.set(mythTransaction);</span><br><span class="line">    <span class="comment">//设置事务上下文，这个类会传递给远端</span></span><br><span class="line">    MythTransactionContext context = <span class="keyword">new</span> MythTransactionContext();</span><br><span class="line">    <span class="comment">//设置事务id</span></span><br><span class="line">    context.setTransId(mythTransaction.getTransId());</span><br><span class="line">    <span class="comment">//设置为发起者角色</span></span><br><span class="line">    context.setRole(MythRoleEnum.START.getCode());</span><br><span class="line">    TransactionContextLocal.getInstance().set(context);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="基于TCC的分布式事务"><a href="#基于TCC的分布式事务" class="headerlink" title="基于TCC的分布式事务"></a>基于TCC的分布式事务</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">pay</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    order.update(order);</span><br><span class="line">    account.decrease(order.num);</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Tcc(confirmMethod=&#x27;&#x27;, cancelMethods=&#x27;&#x27;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">()</span></span>&#123;</span><br><span class="line">&#125;</span><br><span class="line"><span class="meta">@Tcc(confirmMethod=&#x27;&#x27;, cancelMethods=&#x27;&#x27;)</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">decrease</span><span class="params">()</span></span>&#123;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol>
<li><p>使用AOP + Handler的方式，可以把事务相关的事情放到ThreadLocal中。 并且使用Disruptor来处理事务日志，类似于tx-LCN使用RPC框架来持久化调用数据。将数据放入Disruptor队列，异步来进行数据库持久化。当发送Confirm或者Cancel的时候，会先从上下文中查找数据，当数据不存在的时候，从持久化的事务日志中找。这样既保证了宕机后的事务恢复，而且即使是在集群模式中，不同的机器执行confirm或者Cancel也能找到当时的数据。</p>
</li>
<li><p>confirm和cancel通过线程池来延迟处理，提升了并发性能，代码如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Object <span class="title">handler</span><span class="params">(<span class="keyword">final</span> ProceedingJoinPoint point, <span class="keyword">final</span> TccTransactionContext context)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> Throwable </span>&#123;</span><br><span class="line">    Object returnValue;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        TccTransaction tccTransaction = hmilyTransactionExecutor.begin(point);</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//execute try</span></span><br><span class="line">            returnValue = point.proceed();</span><br><span class="line">            tccTransaction.setStatus(TccActionEnum.TRYING.getCode());</span><br><span class="line">            hmilyTransactionExecutor.updateStatus(tccTransaction);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Throwable throwable) &#123;</span><br><span class="line">            <span class="comment">//if exception ,execute cancel</span></span><br><span class="line">            <span class="keyword">final</span> TccTransaction currentTransaction = hmilyTransactionExecutor.getCurrentTransaction();</span><br><span class="line">            executor.execute(() -&gt; hmilyTransactionExecutor</span><br><span class="line">                    .cancel(currentTransaction));</span><br><span class="line">            <span class="keyword">throw</span> throwable;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//execute confirm</span></span><br><span class="line">        <span class="keyword">final</span> TccTransaction currentTransaction = hmilyTransactionExecutor.getCurrentTransaction();</span><br><span class="line">        executor.execute(() -&gt; hmilyTransactionExecutor.confirm(currentTransaction));</span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">        TransactionContextLocal.getInstance().remove();</span><br><span class="line">        hmilyTransactionExecutor.remove();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> returnValue;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="比较"><a href="#比较" class="headerlink" title="比较"></a>比较</h2><table>
<thead>
<tr>
<th align="left">介绍</th>
<th align="left">优点</th>
<th align="left">缺点</th>
</tr>
</thead>
<tbody><tr>
<td align="left">2PC</td>
<td align="left">不侵入业务</td>
<td align="left">研发成本，以及无法回滚Redis以及搜索引擎等情况</td>
</tr>
<tr>
<td align="left">通过消息确保调用持续下去</td>
<td align="left">理念比较简单</td>
<td align="left">适用性低</td>
</tr>
<tr>
<td align="left">TCC</td>
<td align="left">定制化程度高，性能高</td>
<td align="left">需要大量的业务代码</td>
</tr>
</tbody></table>
</li>
</ol>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>本文并没有对各个分布式框架做性能上的压测以及可靠性的检验，只是通过分析各个不同框架实现分布式事务的理念。可以看到，想要不侵入业务层就需要对框架做更多的优化，对于性能也是一个很大的考验。因此，笔者更倾向于使用TCC业务层级的框架来实现。</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blog/tags/%E6%8A%80%E6%9C%AF/" rel="tag"># 技术</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blog/2018/10/10/2018/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="prev" title="设计模式">
      <i class="fa fa-chevron-left"></i> 设计模式
    </a></div>
      <div class="post-nav-item">
    <a href="/blog/2018/10/23/2018/Lua%E8%AF%AD%E8%A8%80%E5%88%9D%E6%8E%A2/" rel="next" title="Lua语言初探">
      Lua语言初探 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let activeClass = CONFIG.comments.activeClass;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#XA%E8%A7%84%E8%8C%83"><span class="nav-number">1.</span> <span class="nav-text">XA规范</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#JTA"><span class="nav-number">2.</span> <span class="nav-text">JTA</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%85%B3%E4%BA%8EXA%E4%BB%A5%E5%8F%8AJTA%E7%9A%84%E6%80%BB%E7%BB%93"><span class="nav-number">3.</span> <span class="nav-text">关于XA以及JTA的总结</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8E2PC%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1"><span class="nav-number">4.</span> <span class="nav-text">基于2PC的分布式事务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%8D%E5%90%8C%E5%AE%B9%E5%99%A8%E4%B9%8B%E9%97%B4%E5%A6%82%E4%BD%95%E6%8E%A7%E5%88%B6%E4%BA%8B%E5%8A%A1%E7%9A%84%E5%9B%9E%E6%BB%9A"><span class="nav-number">4.1.</span> <span class="nav-text">不同容器之间如何控制事务的回滚</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8E%E6%B6%88%E6%81%AF%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1"><span class="nav-number">5.</span> <span class="nav-text">基于消息的分布式事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8ETCC%E7%9A%84%E5%88%86%E5%B8%83%E5%BC%8F%E4%BA%8B%E5%8A%A1"><span class="nav-number">6.</span> <span class="nav-text">基于TCC的分布式事务</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%AF%94%E8%BE%83"><span class="nav-number">7.</span> <span class="nav-text">比较</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">8.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">RunningEgg</p>
  <div class="site-description" itemprop="description">写下我的点点滴滴，写下我对这个世界的看法，还有我内心锁崇拜的技术</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">89</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">24</span>
        <span class="site-state-item-name">tags</span>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="mailto:guodh_1@163.com" title="E-Mail → mailto:guodh_1@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">RunningEgg</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> v5.3.0
  </div>
  <span class="post-meta-divider">|</span>
  <div class="theme-info">Theme – <a href="https://pisces.theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.7.1
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  















  

  

</body>
</html>
